package com.afishing.listener;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

@WebListener
public class OnlineUserListener implements HttpSessionListener {
//    private static int onlineUserCount = -1;

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        ServletContext servletContext = se.getSession().getServletContext();
        System.out.println(se.getSession().getId());
        Integer onlinecount = (Integer) servletContext.getAttribute("OnlineCount");

        if (onlinecount == null) {
            onlinecount = 0;
        } else {
            onlinecount = onlinecount + 1;
        }
        //每次都在更新自己,有累加
        servletContext.setAttribute("OnlineCount", onlinecount);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        ServletContext servletContext = se.getSession().getServletContext();
        Integer onlinecount= (Integer) servletContext.getAttribute("OnlineCount");

        if (onlinecount == null) {
            onlinecount = 0;
        } else {
            onlinecount = onlinecount - 1;
        }
        servletContext.setAttribute("OnlineCount", onlinecount);
    }

//    public static int getOnlineUserCount() {
//        return onlineUserCount;
//    }


}
